package com.peng.my_blog.chat.service;


import com.peng.my_blog.chat.config.WebSocketConfig;
import com.peng.my_blog.chat.entity.Msg;
import com.peng.my_blog.chat.enums.MsgType;
import com.peng.my_blog.chat.util.JsonUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author wangshipeng
 * @Description: websocket服务
 * @date 2019-01-17 15:18
 */
@ServerEndpoint(value = "/websocket/{userCode}", configurator = WebSocketConfig.class)
@Component
public class WebSocketServer {

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketService对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private String currentUser;
    private static ConcurrentLinkedQueue<Msg> chatHistoryList = new ConcurrentLinkedQueue<>();

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userCode") String currentUser, Session session, EndpointConfig config) {
        this.session = session;
        this.currentUser = RandomStringUtils.randomNumeric(5);

        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入！当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        System.out.println("来自的用户id：" + currentUser);
        System.out.println("来自客户端的消息:" + message);
        Msg msg = JsonUtil.string2Obj(message, Msg.class);
        assert msg != null;
        //单发
        if (msg.getMsgType() == MsgType.SEND_ONE) {
            this.sendMessageTo(message, String.valueOf(msg.getToUser().getId()));
            return;
        }
        //群发
        msg.setSendDate(new Date());
        chatHistoryList.offer(msg);
        System.out.println(chatHistoryList);
        this.sendInfo(message);
    }

    /**
     * @param session
     * @param error
     * @return
     * @Description 发生错误时调用
     * @author wangshipeng
     * @date 2019年01月17日 15:20:41
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    /**
     * @param message
     * @return
     * @Description 群发自定义消息
     * @author wangshipeng
     * @date 2019年01月17日 15:21:06
     */
    public void sendInfo(String message) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            try {
                if (!item.currentUser.equals(currentUser))
                    item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public void sendMessageTo(String message, String userCode) throws IOException {
        for (WebSocketServer item : webSocketSet) {
            if (item.currentUser.equals(userCode)) {
                item.session.getBasicRemote().sendText(message);
                return;
            }
        }
    }
}
